#ifndef __ILIB_CORE_MSG_THREAD_H_20120131__
#define __ILIB_CORE_MSG_THREAD_H_20120131__

#include "../h/iThread.h"
#include "../h/iMsg.h"
#include "iRingQueue.h"

class iMsgThread : public iThread
				 , public iMsg::iSink
{
public:
	iMsgThread(void);
	virtual ~iMsgThread(void);

public:
    inline uint32_t get_index() { return m_index; }
	inline void post_msg(iMsg* msg, iMsgThread* thd)
    {
        if(m_q_slots[thd->get_index()]==NULL)
            m_q_slots[thd->get_index()] = new iRingQueue<iMsg>();

        m_q_slots[thd->get_index()]->push(msg);
    }
    inline iMsg* get_message()
    {
        iMsg* msg = NULL;
        for(uint32_t i=0; i<256; ++i)
        {
            if(m_q_slots[i]==NULL)
                continue;

            if(i == m_index)
                continue;
            
            msg = m_q_slots[i]->pop();
            if(msg)
                return msg;
        }

        msg = m_q_slots[m_index]->pop();
		return msg;
    }

protected:
	virtual int on_message(iMsgID msg, void* param);
	virtual int run();

protected:
    std::vector< iRingQueue<iMsg>* > m_q_slots;
    uint32_t    m_index;

protected:
    static uint8_t  s_index;

};

#endif  //__ILIB_CORE_MSG_THREAD_H_20120131__
